package com.zzyl.nursing.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.NursingTaskDto;
import com.zzyl.nursing.dto.TaskDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.NursingElderMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.util.IDCardUtils;
import com.zzyl.nursing.vo.NursingNameVo;
import com.zzyl.nursing.vo.NursingTaskVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.NursingTaskMapper;
import com.zzyl.nursing.domain.NursingTask;
import com.zzyl.nursing.service.INursingTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import static org.apache.commons.collections4.CollectionUtils.collect;

/**
 * 护理任务Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-02
 */
@Service
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper, NursingTask> implements INursingTaskService {
    @Autowired
    private NursingTaskMapper nursingTaskMapper;
    @Autowired
    private NursingElderMapper nursingElderMapper;

    /**
     * 查询护理任务
     *
     * @param nursingTaskDto@return 护理任务
     */
    @Override
    public TableDataInfo selectNursingTaskList(NursingTaskDto nursingTaskDto) {
        //分页查询
        PageHelper.startPage(nursingTaskDto.getPageNum(), nursingTaskDto.getPageSize());
        //执行sql
        List<NursingTask> nursingTasks = nursingTaskMapper.selectByPage(nursingTaskDto);
        Page<NursingTask> page = (Page<NursingTask>) nursingTasks;
        List<NursingTask> records = page.getResult();
        Set<Long> userIds = new HashSet<>();
        //拼装护理员列表ID
        nursingTasks.forEach(nursingTask -> {
            if (StringUtils.isNotEmpty(nursingTask.getNursingId())) {
                String[] split = nursingTask.getNursingId().split(",");
                for (String nid : split) {
                    userIds.add(Long.valueOf(nid));
                }
            }
        });
        //如果护理员列表为空，则直接返回
        if (CollUtil.isEmpty(nursingTasks) || CollUtil.isEmpty(userIds)) {
            return getTableDataInfo(page, records);
        }
        //通过nursing_id获取老人对应的护理员信息
        List<NursingNameVo> nursingNameVoList = nursingElderMapper.selectNickNameByElderId(userIds);
        //转换为map，key:id,value:护理员列表
        Map<Long, List<NursingNameVo>> listMap = nursingNameVoList.stream().collect(Collectors.groupingBy(NursingNameVo::getElderId));
        records.forEach(nursingTask -> {
            List<NursingNameVo> nursingNameVos = listMap.get(nursingTask.getElderId());
            List<String> nursingNameStrList = nursingNameVos.stream().map(NursingNameVo::getNursingName).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(nursingNameStrList)) {
                nursingTask.setNursingName(nursingNameStrList);
            }
        });
        return getTableDataInfo(page, records);
    }

    private TableDataInfo getTableDataInfo(Page page, List<NursingTask> records) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setMsg("请求成功");
        tableDataInfo.setCode(200);
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(records);
        return tableDataInfo;
    }

    @Autowired
    private ICheckInService ccheckInService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 获取护理任务详细信息
     *
     * @param id
     */
    @Override
    public NursingTaskVo getInfo(Long id) {
//        获取老人信息
        NursingTask nursingTask = getById(id);
        if (BeanUtil.isEmpty(nursingTask)) {
            log.error("获取护理任务失败");
        }
//        获取护理等级
        NursingTaskVo nursingTaskVo = new NursingTaskVo();
        BeanUtil.copyProperties(nursingTask, nursingTaskVo);
        LambdaQueryWrapper<CheckIn> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(CheckIn::getElderId, nursingTask.getElderId());
        CheckIn checkInfo = ccheckInService.getOne(queryWrapper);
        if(BeanUtil.isEmpty(queryWrapper)){
            log.error("获取入住信息失败");
        }
        nursingTaskVo.setNursingLevelName(checkInfo.getNursingLevelName());
//        获取护理员列表
        List<SysUser> sysUserList=nursingElderMapper.selectUserByElderId(nursingTask.getElderId());
        List<String> list = sysUserList.stream().map(sysUser->sysUser.getNickName()).collect(Collectors.toList());
        nursingTaskVo.setNursingName(list);



//        获取年龄
        Elder elder =elderMapper.selectElderById(nursingTask.getElderId());
        nursingTaskVo.setAge(IDCardUtils.getAgeByIdCard(elder.getIdCardNo()));

//        设置性别
        nursingTaskVo.setSex(elder.getSex()==0?"女":"男");
//        获取执行人
    if (StringUtils.isNotEmpty(nursingTask.getUpdateBy())){

        SysUser sysUser=sysUserService.selectUserById(Long.valueOf(nursingTask.getUpdateBy()));
        nursingTaskVo.setUpdater(sysUser.getNickName());
    }
        return nursingTaskVo;
    }

    /**
     * 取消任务
     *
     * @param taskDto
     */
    @Override
    public int cancel(TaskDto taskDto) {
//        查询任务
        NursingTask nursingTask=getById(taskDto.getTaskId());
//        判断任务是否存在
        if (ObjectUtil.isEmpty(nursingTask)){
            log.error("取消任务失败");
            throw new BaseException("任务不存在");
        }
//        修改状态
        nursingTask.setStatus(3);
        nursingTask.setCancelReason(taskDto.getReason());
        return updateById(nursingTask) ? 1 : 0;
    }

    /**
     * 执行任务
     *
     * @param taskDto
     */
    @Override
    public int doTask(TaskDto taskDto) {
//        查询任务
        NursingTask nursingTask=getById(taskDto.getTaskId());
//        判断任务是否存在
        if (ObjectUtil.isEmpty(nursingTask)){
            throw new BaseException("任务不存在");
        }
//        修改执行
        nursingTask.setStatus(2);
        nursingTask.setRealServerTime(taskDto.getEstimatedServerTime());
        nursingTask.setTaskImage(taskDto.getTaskImage());
        nursingTask.setMark(taskDto.getMark());
//        nursingTask.setId(taskDto.getTaskId());
        return updateById(nursingTask) ? 1 : 0;
    }

    /**
     * 任务改期
     *
     * @param taskDto
     */
    @Override
    public int updateTimeTask(TaskDto taskDto) {
//        查询任务
        NursingTask nursingTask=getById(taskDto.getTaskId());
//        判断任务是否存在
        if (ObjectUtil.isEmpty(nursingTask)){
            throw new BaseException("任务不存在");
        }
//        任务改期
        nursingTask.setEstimatedServerTime(taskDto.getEstimatedServerTime());
        return updateById(nursingTask) ? 1 : 0;
    }
}
